/*
 * test.c
 *
 *  Created on: Apr 21, 2021
 *      Author: soliber
 */

#include "main.h"
#include <stdio.h>
#include <stdlib.h>
#include "usart.h"
#include "fsmc.h"

#define BANK1_BASE 0x60000000U

//对指定地址进行填充测试
int fill_test_16b(uint32_t *addr) {
	uint16_t wb, rb;
	//写一个16bit随机数
	wb = rand();
	HAL_SRAM_Write_16b(&hsram1, addr, &wb, 1);
	//读取
	HAL_SRAM_Read_16b(&hsram1, addr, &rb, 1);
	//判断
	return wb==rb?0:1;
}

//测试
void test(void) {

	uint32_t mode, base, len;

	printf("FSMC Test (Muxed PSRAM).\r\n");

	while(1)
	{
		uint32_t error = 0, dat = 0;

		//输入模式
		printf("\r\nplease select test mode:\r\n"
				"1: Single read (8bit)\r\n"
				"2: Continuous read (8bit)\r\n"
				"3: Single read (16bit)\r\n"
				"4: Continuous read (16bit)\r\n"
				"");
		scanf("%d",&mode);
		printf("mode:%d\r\n",mode);

		//输入地址
		printf("\r\nplease input the address (0x00000000~0x0fffffff):\r\n");
		scanf("%x", &base);
		printf("0x%08x\r\n",base);

		//判断是否连续模式
		if(mode == 2 || mode ==4)
		{
			//输入数据长度
			printf("please input the data length (half word):\r\n");
			scanf("%d", &len);
			printf("%d\r\n",len);
		}

		//根据用户选择的模式进行操作
		switch(mode)
		{
		case 1:	//Single read (8bit)
			HAL_SRAM_Read_8b(&hsram1, base+BANK1_BASE, &dat, 1);
			printf("read:\r\n");
			printf("0x%02x\r\n",dat);
			break;
		case 2:	//Continuous read (8bit)
			printf("read:\r\n");
			for(uint32_t addr = base; addr < base +len*2;addr+=2)
			{
				HAL_SRAM_Read_8b(&hsram1, addr+BANK1_BASE, &dat, 1);
				printf("0x%02x(@0x%08x)\r\n",dat,addr);
			}
			break;
		case 3:	//Single read (16bit)
			if(base%2)
			{
				printf("Misaligned address!\r\n");
				break;
			}
			HAL_SRAM_Read_16b(&hsram1, base+BANK1_BASE, &dat, 1);
			printf("0x%04x\r\n",dat);
			break;
		case 4:	//Continuous read (16bit)
			if(base%2)
			{
				printf("Misaligned address!\r\n");
				break;
			}
			printf("read:\r\n");
			for(uint32_t addr = base; addr < base +len*2;addr+=2)
			{
				HAL_SRAM_Read_16b(&hsram1, addr+BANK1_BASE, &dat, 1);
				printf("0x%04x(@0x%08x)\r\n",dat,addr);
			}
			break;
		default:
			printf("Unsupported mode!\r\n");
		}
	}
}
